package cn.hackcloud.mutithread.juc;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 *
 * @author hackcloud
 */
public class TestReadWriteLock {
    public static void main(String[] args) {
        ReadWriteLockDemo demo = new ReadWriteLockDemo();
        new Thread(() -> {
            demo.set((int) (Math.random() * 101));
        }, "Write").start();

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                demo.get();
            }, "Read").start();
        }

    }
}

class ReadWriteLockDemo {
    ReadWriteLock lock = new ReentrantReadWriteLock();
    int num = 0;

    public void get() {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + ":" + num);
        } finally {
            lock.readLock().unlock();
        }
    }

    public void set(int num) {
        lock.writeLock().lock();
        try {
            this.num = num;
            System.out.println(Thread.currentThread().getName() + ":" + num);
        } finally {
            lock.writeLock().unlock();
        }
    }
}